#import "HHAlertSheetController.h"
#import "HHSheetAlertControllerAnimated.h"

#import <BCComConfigKit/BCComConfig.h>
#import <BCFoundation/BCFoundation.h>
#import <BCUIKit/BCUIKit.h>
#import <Masonry/Masonry.h>

@interface HHAlertSheetController ()
<
    UITableViewDelegate,
    UITableViewDataSource,
    HHSheetAlertAnimatedController
>
/// 每行高度 默认：56
@property (nonatomic, assign) CGFloat rowHeight;
/// 阴影
@property (nonatomic, strong) UIControl *shadeControl;
@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) UITableView *tableView;


@property (nonatomic, strong) NSAttributedString *attributedTitle;
@property (nonatomic, strong) NSString *cancelTitle;

@end

@implementation HHAlertSheetController

///MARK: - system
- (instancetype)init {
    self = [super init];

    if (self) {
        self.modalPresentationStyle = UIModalPresentationCustom;
        self.transitioningDelegate = (id<UIViewControllerTransitioningDelegate>)self;
        self.enableAtIndex = -1;
        self.rowHeight = 56;
    }

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initializePageSubviews];
}

///MARK: - public
+ (HHAlertSheetController *)shoWithTitle:(nullable NSString *)title list:(NSArray *)dataList completion:(void (^_Nullable)(NSInteger index))completion {
    return [self shoWithTitle:title list:dataList cancelTitle:@"取消" completion:completion];
}

+ (HHAlertSheetController *)shoWithTitle:(nullable NSString *)title list:(NSArray *)dataList cancelTitle:(nullable NSString *)cancelTitle completion:(void (^_Nullable)(NSInteger index))completion {
    return [self showTitle:title orAttributedTitle:nil list:dataList cancelTitle:cancelTitle completion:completion];
}

+ (HHAlertSheetController *)shoWithTitle:(nullable NSString *)title list:(NSArray *)dataList itemHeight:(CGFloat)height cancelTitle:(nullable NSString *)cancelTitle completion:(void (^_Nullable)(NSInteger index))completion {
    return [self showTitle:nil orAttributedTitle:title list:dataList itemHeight:height cancelTitle:cancelTitle completion:completion];
}

+ (HHAlertSheetController *)showAttributedTitle:(nullable NSAttributedString *)attributedTitle list:(NSArray *)dataList cancelTitle:(nullable NSString *)cancelTitle completion:(void (^_Nullable)(NSInteger index))completion {
    return [self showTitle:nil orAttributedTitle:attributedTitle list:dataList cancelTitle:cancelTitle completion:completion];
}

+ (HHAlertSheetController *)showTitle:(nullable NSString *)title orAttributedTitle:(nullable NSAttributedString *)attributedTitle list:(NSArray *)dataList cancelTitle:(nullable NSString *)cancelTitle completion:(void (^_Nullable)(NSInteger index))completion {
    return [self showTitle:nil orAttributedTitle:attributedTitle list:dataList itemHeight:0 cancelTitle:cancelTitle completion:completion];
}

+ (HHAlertSheetController *)showTitle:(nullable NSString *)title orAttributedTitle:(nullable NSAttributedString *)attributedTitle list:(NSArray *)dataList itemHeight:(CGFloat)height cancelTitle:(nullable NSString *)cancelTitle completion:(void (^_Nullable)(NSInteger index))completion {
    HHAlertSheetController *sheetController = [[HHAlertSheetController alloc] init];

    if (title) {
        sheetController.title = title;
    }

    if (attributedTitle) {
        sheetController.attributedTitle = attributedTitle;
    }

    if (height > 1) {
        sheetController.rowHeight = height;
    }

    sheetController.cancelTitle = cancelTitle;
    sheetController.dataArr = dataList;
    sheetController.selectedBlock = completion;


    UIViewController *topPage = [UIApplication sharedApplication].keyWindow.rootViewController;
    [topPage presentViewController:sheetController animated:YES completion:NULL];

    return sheetController;
}

///MARK: - setter
- (void)setDataArr:(NSArray *)dataArr {
    _dataArr = dataArr;

    [self.tableView reloadData];
}
- (void)setEnableAtIndex:(NSInteger)enableAtIndex {
    _enableAtIndex = enableAtIndex;
    [self.tableView reloadData];
}

///MARK: - private
- (void)dismissSelfPage {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

///MARK: - Control
- (void)handleCancelButtonEvent:(id)sender {
    [self dismissSelfPage];
}

///MARK: - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *alertCellIdentifier = @"kalertCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:alertCellIdentifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:alertCellIdentifier];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.font = BCComConfig.config.bcBoldFont(16);
        cell.textLabel.textColor = BCComConfig.config.blackColor;
        cell.textLabel.numberOfLines = 0;

        // separator
        UIImageView *separatorView = [[UIImageView alloc] init];
        separatorView.backgroundColor = BCComConfig.config.splitColor;
        separatorView.tag = 200;
        [cell.contentView addSubview:separatorView];

        [separatorView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(cell.contentView);
            make.height.mas_equalTo(0.6f);
        }];
    }

    id value = [self.dataArr bc_safeObjectAtIndex:indexPath.row];

    if ([value isKindOfClass:[NSAttributedString class]]) {
        cell.textLabel.attributedText = value;
    } else {
        cell.textLabel.text = value;
    }
    if(indexPath.row == self.enableAtIndex){
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }else{
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    }

    UIImageView *separatorView = [cell.contentView viewWithTag:200];
    separatorView.hidden = indexPath.row == self.dataArr.count - 1;
    return cell;
}

///MARK: - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.rowHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (self.selectedBlock) {
        self.selectedBlock(indexPath.row);
    }
    if(indexPath.row == self.enableAtIndex) {
        return;
    }
    [self dismissSelfPage];
}

///MARK: - HHSheetAlertAnimatedController
- (UIView *)animateAlertView {
    return self.contentView;
}

///MARK: - UIViewControllerAnimatedTransitioning
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [[HHSheetAlertControllerAnimated alloc]init];
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [[HHSheetAlertControllerAnimated alloc]init];
}

///MARK: - Page subviews
- (void)updateAlertContentLayout {
    if (!self.contentView.superview) {
        return;
    }

    if (self.dataArr.count < 1) {
        return;
    }

    CGFloat contentHeight = (self.dataArr.count * self.rowHeight) + kBCScreenSafeFitBottom;

    if (self.title.length > 1) {
        contentHeight += 50;
    }

    if (self.attributedTitle) {
        contentHeight += 66;
    }

    if (self.cancelTitle) {
        // 62 = 54+8
        contentHeight += 62;
    }

// 设定最大值不超过屏幕-160
    contentHeight = MIN(kBCSCREEN_HEIGHT - 160, contentHeight);

    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(contentHeight);
        make.height.mas_equalTo(contentHeight);
    }];
    [_shadeControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.contentView.mas_top);
    }];
}

- (void)initializePageSubviews {
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6f];

    [self.view addSubview:self.shadeControl];
    [self.view addSubview:self.contentView];

    [self updateAlertContentLayout];

    // 头
    CGFloat headerHeight = 0;

    if (self.title.length > 0 || self.attributedTitle) {
        UIView *headView = [[UIView alloc] init];
        [headView addSubview:self.titleLab];
        [self.contentView addSubview:headView];

        headerHeight = self.attributedTitle ? 66 : 50;
        // Constraints
        [headView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.mas_equalTo(self.contentView);
            make.height.mas_equalTo(headerHeight);
        }];
        [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(headView);
        }];

        if (self.attributedTitle) {
            _titleLab.numberOfLines = 0;
            _titleLab.attributedText = self.attributedTitle;
        } else {
            _titleLab.text = self.title;
        }
    }

    CGFloat bottomHeight = kBCScreenSafeFitBottom;

    // 取消
    if (self.cancelTitle) {
        @BCWeakify(self);

        UIButton *cancelBtn = [UIButton bc_allocButton:^(UIButton *_Nonnull btn) {
            btn.titleLabel.font = BCComConfig.config.bcFont(16);
            [btn setBackgroundImage:[UIImage bc_imageWithColor:[UIColor whiteColor]]
                           forState:UIControlStateNormal];

            [btn setTitleColor:BCComConfig.config.blackColor
                      forState:UIControlStateNormal];
            [btn setTitle:self.cancelTitle
                 forState:UIControlStateNormal];
        }
                                                action:^(UIButton *_Nonnull btn) {
            @BCStrongify(self);
            [self dismissSelfPage];
        }];

        // space
        UIView *spaceView = [[UIView alloc] init];
        spaceView.backgroundColor = [UIColor bc_colorWithRGB:0xF7F7F7];

        [self.contentView addSubview:cancelBtn];
        [self.contentView addSubview:spaceView];

        [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.contentView);
            make.bottom.mas_equalTo(-kBCScreenSafeFitBottom);
            make.height.mas_equalTo(54);
        }];
        [spaceView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.contentView);
            make.bottom.mas_equalTo(cancelBtn.mas_top);
            make.height.mas_equalTo(8);
        }];

        bottomHeight += 62;
    }

    [self.contentView addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(headerHeight);
        make.left.right.mas_equalTo(self.contentView);
        make.bottom.mas_equalTo(-bottomHeight);
    }];
}

///MARK: -getter
- (UIControl *)shadeControl {
    if (!_shadeControl) {
        _shadeControl = [[UIControl alloc] initWithFrame:self.view.bounds];
        [_shadeControl addTarget:self action:@selector(handleCancelButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    }

    return _shadeControl;
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBCSCREEN_WIDTH, 100)];
        _contentView.layer.masksToBounds = YES;
        _contentView.layer.cornerRadius = 12;
        _contentView.clipsToBounds = YES;
        _contentView.backgroundColor = [UIColor whiteColor];
    }

    return _contentView;
}

- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [UILabel bc_allocLable:^(UILabel *_Nonnull label) {
            label.font = BCComConfig.config.bcFont(14);
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = BCComConfig.config.littleBlackColor;
            label.text = self.title;
        }];
    }

    return _titleLab;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.contentView.bounds style:UITableViewStyleGrouped];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _tableView.separatorColor = kBCRGBColor(0xEFEFEF);
        _tableView.backgroundColor = [UIColor redColor];
        _tableView.estimatedSectionHeaderHeight = 0.f;
        _tableView.estimatedSectionFooterHeight = 0.f;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.bounces = NO;
        _tableView.scrollEnabled = NO;

        if (@available(iOS 11, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }

    return _tableView;
}

@end
